/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.*;
import com.jeeplus.modules.ap.service.YueService;
import com.jeeplus.modules.ap.util.Export;
import com.jeeplus.modules.infor.entity.Department;
import com.jeeplus.modules.infor.entity.Staff;
import com.jeeplus.modules.infor.service.DepartmentService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.UnableToInterruptJobException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.service.ExpenditureService;

/**
 * 支出Controller
 * @author slD
 * @version 2017-11-30
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/expenditure")
public class ExpenditureController extends BaseController {

	@Autowired
	private ExpenditureService expenditureService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private YueService yueService;
	@Autowired
	private DepartmentService departmentService;
	@ModelAttribute
	public Expenditure get(@RequestParam(required = false) String id) {
		Expenditure entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = expenditureService.get(id);
		}
		if (entity == null) {
			entity = new Expenditure();
		}
		return entity;
	}

	/**
	 * 支出列表页面
	 */
	@RequiresPermissions("ap:expenditure:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/expenditureList";
	}

	/**
	 * 支出列表页面
	 */
	@RequiresPermissions("ap:expenditure:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/ap/2/expenditureList";
	}

	/**
	 * 支出列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:expenditure:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Expenditure expenditure, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			expenditure.setProjectName(projectService.findUniqueByProperty("name",pro));}
		Page<Expenditure> page = expenditureService.findPage(new Page<Expenditure>(request, response), expenditure);
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequestMapping(value="cx")
	public String cx(String min,String max,String pro,String dx,String gs){
		Expenditure i=new Expenditure();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			i.setProjectName(projectService.get(pro));
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				i.setProjectName(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			}
		}
		i.setMinDate(min);
		i.setMax(max);
		i.setCostObject(dx);
		i.setCostAffiliation(gs);
		i.setDocumentStatus("财务已审批");
		List<Expenditure> list=expenditureService.findList(i);
		double xj=0.0;
		double yk=0.0;
		String ids="";
		for(Expenditure in:list){
			ids+=in.getId()+",";
			if(in.getType().equals("现金")){
				xj+=in.getMoney();
			}else{
				yk+=in.getMoney();
			}

		}
		NumberFormat nf = NumberFormat.getInstance();
		i.setMoney(Double.parseDouble(nf.format(xj).replaceAll(",","")));
		i.setDepartment(nf.format(yk));
		i.setMax(ids);
		list.add(i);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Expenditure> list =new ArrayList<Expenditure>();
		for(String id:idd){
			list.add(expenditureService.get(id));
		}

		Export e=new Export();
		e.exportexpenditure(response,list);
	}
	/**
	 * 支出列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:expenditure:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Expenditure expenditure, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		expenditure.setDocumentStatus("总经理已审批");
		if(!pro.equals("总部")){
			expenditure.setProjectName(projectService.findUniqueByProperty("name",pro));}
		Page<Expenditure> page = expenditureService.findPage(new Page<Expenditure>(request, response), expenditure);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑支出表单页面
	 */
	@RequiresPermissions(value = {"ap:expenditure:view", "ap:expenditure:add", "ap:expenditure:edit"}, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(Expenditure expenditure, Model model) {
		if(expenditure.getIsNewRecord()){
			expenditure.setDocumentStatus("已创建");
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				expenditure.setProjectName(projectService.findUniqueByProperty("name",pro));}
			Department d=departmentService.findUniqueByProperty("project",projectService.findUniqueByProperty("name",pro).getId());
			expenditure.setDepartment(d.getName());
				Expenditure i=new Expenditure();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			i.setDocumentNumber(code);
			List<Expenditure> list=expenditureService.findList(i);
			if(list==null||list.size()<1){
				expenditure.setDocumentNumber(code+"001"+"ZC");
			}else{
				if(list.size()/10==0){
					expenditure.setDocumentNumber(code+"00"+(list.size()+1)+"ZC");
				}else
				if(list.size()/100==0){
					expenditure.setDocumentNumber(code+"0"+(list.size()+1)+"ZC");
				}else{expenditure.setDocumentNumber(code+(list.size()+1)+"ZC");}

			}
			Staff staff =new Staff();
			staff.setProjectName(UserUtils.getUseroffice());
			List<Staff> l=staffService.findList(staff);
			for(Staff s:l){
				if(staffService.get(s.getId()).getPosition().getName().contains("财务")){
					expenditure.setResponsiblePerson(s);
				}
			}
		}

		model.addAttribute("expenditure", expenditure);
		return "modules/ap/expenditureForm";
	}

	/**
	 * 保存支出
	 */
	@ResponseBody
	@RequiresPermissions(value = {"ap:expenditure:add", "ap:expenditure:edit"}, logical = Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Expenditure expenditure, Model model, RedirectAttributes redirectAttributes) throws Exception {
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, expenditure)) {
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		expenditureService.save(expenditure);//保存
		List<DetailsExpenditure> list=expenditure.getDetailsExpenditureList();
		if(list!=null&&list.size()>0){
		Double d=0.0;
		for(DetailsExpenditure de:list){
			d+=Double.parseDouble(de.getTotal());
		}
		NumberFormat nf = NumberFormat.getInstance();
		expenditure.setMoney(Double.parseDouble(nf.format(d).replaceAll(",","")));
		expenditureService.save(expenditure);//保存
		}j.setSuccess(true);
		j.setMsg("保存支出成功");
		return j;
	}

	/**
	 * 删除支出
	 */
	@ResponseBody
	@RequiresPermissions("ap:expenditure:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Expenditure expenditure, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		expenditureService.delete(expenditure);
		j.setMsg("删除支出成功");
		return j;
	}
	/**
	 * 删除支出
	 */
	@ResponseBody
	@RequestMapping(value = "bh")
	public AjaxJson bh(String i, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		Expenditure expenditure=expenditureService.get(i);
		expenditure.setDocumentStatus("审核未通过");
		expenditureService.save(expenditure);
		j.setMsg("驳回成功");
		return j;
	}
	/**
	 * 确认提交
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(Expenditure expenditure, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		expenditure.setDocumentStatus("已确认待审批");
		expenditureService.save(expenditure);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 批量删除支出
	 */
	@ResponseBody
	@RequiresPermissions("ap:expenditure:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			expenditureService.delete(expenditureService.get(id));
		}
		j.setMsg("删除支出成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:expenditure:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(Expenditure expenditure, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "支出" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Expenditure> page = expenditureService.findPage(new Page<Expenditure>(request, response, -1), expenditure);
			new ExportExcel("支出", Expenditure.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出支出记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "detail")
	public Expenditure detail(String id) {
		return expenditureService.get(id);
	}


	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("ap:expenditure:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Expenditure> list = ei.getDataList(Expenditure.class);
			for (Expenditure expenditure : list) {
				try {
					expenditureService.save(expenditure);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条支出记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条支出记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入支出失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ap/expenditure/?repage";
	}

	/**
	 * 下载导入支出数据模板
	 */
	@RequiresPermissions("ap:expenditure:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "支出数据导入模板.xlsx";
			List<Expenditure> list = Lists.newArrayList();
			new ExportExcel("支出数据", Expenditure.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ap/expenditure/?repage";
	}



	@RequestMapping(value = "expendStatus")
	@ResponseBody
	public String expendStatus(Expenditure expenditure, HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter("ids");
		if (StringUtils.isNotEmpty(ids)) {
			String[] str = ids.split(",");
			if (str != null && str.length > 0) {
				for (String id : str) {
					if (StringUtils.isNotEmpty(id)) {
						expenditure = expenditureService.get(id);
						String position=UserUtils.getposition();
						if(position.equals("办事处经理")){
							expenditure.setDocumentStatus("经理已审批");
						}
						if(position.contains("总监")){
							expenditure.setDocumentStatus("总监已审批");
						}
						if(position.equals("总经理")){
							NumberFormat nf = NumberFormat.getInstance();
							Yue yue=yueService.findUniqueByProperty("pro",expenditure.getProjectName().getName());
							if(expenditure.getType().equals("现金")){
								yue.setXj(nf.format(Double.parseDouble(yue.getXj())-expenditure.getMoney()).replaceAll(",",""));
							}else{
								yue.setYk(nf.format(Double.parseDouble(yue.getYk())-expenditure.getMoney()).replaceAll(",",""));
							}

							yue.setZje(nf.format(Double.parseDouble(yue.getZje())-expenditure.getMoney()).replaceAll(",",""));
							yueService.save(yue);
							expenditure.setDocumentStatus("总经理已审批");
						}
						expenditureService.save(expenditure);
					}


				}
			}


		}


		return "succe";
	}


}